package cn.xsshome.mvcdo.controller.rest;

import cn.xsshome.mvcdo.common.AIConstant;
import cn.xsshome.mvcdo.common.AipAdded;
import cn.xsshome.mvcdo.interceptor.BDFactory;
import cn.xsshome.mvcdo.service.AnalysisORCTool;
import cn.xsshome.mvcdo.service.ai.baidu.BDOCRDetectService;
import cn.xsshome.mvcdo.util.FileUtil;
import cn.xsshome.mvcdo.util.PrintUtil;
import cn.xsshome.mvcdo.vo.BDConstant;
import cn.xsshome.mvcdo.vo.BDDishResponse;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping(value="rest/ocr")
@Scope("prototype")
@SuppressWarnings("all")
public class BDOcrRestController {
	private static Logger logger = LoggerFactory.getLogger(BDOcrRestController.class);
	AipOcr aipOcr = BDFactory.getAipOcr();
	AipAdded aipAdded = BDFactory.getAipAdded();
	@Autowired
	private BDOCRDetectService bdocrDetectService;
	@Autowired
	private AnalysisORCTool orclTool;


	/**
	 * 文字识别网页上传
	 * @param request request对象
	 * @param response response对象
	 * @return 页面
	 */
	@RequestMapping(value="/index")
	public String index(HttpServletRequest request,HttpServletResponse response){
		logger.info("index跳转图像识别网页==访问的ip:"+request.getRemoteAddr());
		return "rest/bdicrfile";
	}
	 @RequestMapping(value = "/detect",method = {RequestMethod.POST})
	 public String uploadOcr(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request, HttpServletResponse response){
         return this.myUpload(file,request,response);
	}


	@RequestMapping(value = "/detect/v2",method = {RequestMethod.POST})
	public String uploadOcrV2(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request, HttpServletResponse response){
            return this.myUpload(file,request,response);
	}

	private String myUpload(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        String resultData = "";
		BDDishResponse bdDishResponse = new BDDishResponse();
        String ocrtype = request.getParameter("ocrtype");
        String clientType = request.getParameter("clientType");
        String openId = ServletRequestUtils.getStringParameter(request, "openId","");
        String nickName = ServletRequestUtils.getStringParameter(request, "nickName","");

        logger.info("=======访问的IP"+request.getRemoteAddr()+"======访问的User-Agent:"+request.getHeader("User-Agent"));
        logger.info("=======访问的类型"+clientType+"=======访问的接口类型"+ocrtype);
        if(null==ocrtype ){
            bdDishResponse.setCode(BDConstant.BD_NULL.getCode().toString());
            bdDishResponse.setMsg(BDConstant.BD_NULL.getMsg());
            resultData = JSON.toJSONString(bdDishResponse);
            logger.info("=====接口返回的内容:"+resultData);
            PrintUtil.printJson(response,resultData);
			return null;
        }

		String perfix = "ocrGeneral/";
		String dbPath ="/"+perfix;
		String fileName = "ocrBD"+new Date().getTime()/1000+FileUtil.fileType(file.getOriginalFilename());
		String filePath = request.getSession().getServletContext().getRealPath(perfix);
		logger.info("=======保存的路径"+filePath+"/"+fileName);
		try {
			nickName = URLEncoder.encode(nickName, "UTF-8");
			if("web".equals(clientType)){
				if(null==request.getHeader("User-Agent")){
					bdDishResponse.setCode(BDConstant.BD_403.getCode().toString());
					bdDishResponse.setMsg(BDConstant.BD_403.getMsg());
				}else{
					bdDishResponse.setCode(BDConstant.BD_NOTFUND.getCode().toString());
					bdDishResponse.setMsg(BDConstant.BD_NOTFUND.getMsg());
				}
			}else if ("wsc".equals(clientType)) {
				String authCode = request.getParameter("authCode");
				if(null==authCode|| "".equals(authCode) || !authCode.equals(AIConstant.AUTH_CODE)){
					bdDishResponse.setCode(BDConstant.BD_NOTFUND.getCode().toString());
					bdDishResponse.setMsg(BDConstant.BD_NOTFUND.getMsg());
				}
			}
			logger.info("=====filePath:{},fileName:{},",filePath+"/",fileName);
			FileUtil.uploadFile(file.getBytes(),filePath+"/",fileName);
			System.out.println("end====="+new Date().getTime());
			//图片的本地路径
			String imagePath = filePath+"/"+fileName;
			//设置使用AI相关api参数
			HashMap<String, String> option = new HashMap<String, String>();
			option.put("detect_direction", "true");

			resultData = orclTool.getOCRResult(ocrtype,clientType,dbPath,option,imagePath,openId,nickName);
			dbPath += fileName;
		} catch (Exception e) {
			logger.error("文字识别百度接口出错了====接口类型：", e);
			bdDishResponse.setCode(BDConstant.BD_ERROR.getCode().toString());
			bdDishResponse.setMsg(BDConstant.BD_ERROR.getMsg());
		}
		if(StringUtils.isEmpty(resultData)){
			resultData = JSON.toJSONString(bdDishResponse);
		}
		logger.info("=====接口返回的内容:"+resultData);
		PrintUtil.printJson(response,resultData);
        return null;
    }

}
